package internetware.androidclient;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Client extends Activity {
	private HashMap<String,String> m;
	private boolean running = false;
	private String pfile = "internetwareclientsetting";
	private String server;
	private String timeout;
	private String username;
	private String password;
	private String sessionid;
	private void getSetting()
	{
		SharedPreferences sp = getSharedPreferences(pfile,0);
        m = new HashMap<String,String>();
        String list = sp.getString("list", null);
        if(list!=null)
        {
        	String[] arr  = list.split(":");
        	for(int i=0;i<arr.length;i++)
        	{
        		m.put(arr[i], sp.getString(arr[i], null));
        	}
        }
        server = sp.getString("server", null);
        timeout = sp.getString("timeout", null);
	}
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button enter = (Button) findViewById(R.id.enter);
        Button set = (Button) findViewById(R.id.set);
        Button stop = (Button) findViewById(R.id.stop);
        stop.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				Button enter = (Button) findViewById(R.id.enter);				
				Button stop = (Button) findViewById(R.id.stop);
				stop.setClickable(false);
				enter.setClickable(true);
				running = false;
			}
        	
        });
        stop.setClickable(false);
        set.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent itemintent = new Intent(Client.this,Set.class);			
				itemintent.putExtra("server", server);
				itemintent.putExtra("timeout", timeout);
				startActivityForResult(itemintent, 0);
			}       	
        });
        enter.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				getSetting();
				//server = "http://192.168.0.12/put_context/";
				//timeout = "10";
				EditText e1 = (EditText) findViewById(R.id.username);
				username = e1.getText().toString();
				EditText e2 = (EditText) findViewById(R.id.password);
				password = e2.getText().toString();
				if(username.equals("")||password.equals(""))
				{
					return;
				}
				if(!m.keySet().contains(username))
				{
					Intent itemintent = new Intent(Client.this,Device.class);			
					itemintent.putExtra("user", username);
					startActivityForResult(itemintent, 0);
				}
				else
				{
					String res = login();
					if(!res.contains("sessionid"))
					{					
						Toast.makeText(Client.this, res, Toast.LENGTH_LONG).show();
					}
					else
					{
						sessionid = res.substring(res.indexOf(":")+1);
						//Toast.makeText(Client.this, sessionid, Toast.LENGTH_LONG).show();
						running  = true;
						Button stop = (Button) findViewById(R.id.stop);
						stop.setClickable(true);
						Button enter = (Button) findViewById(R.id.enter);
						enter.setClickable(false);
						innerThread t = new innerThread();
						t.start();
					}
				}
			}       	
        });
        CompleteReceiver receiver = new CompleteReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("clientandroid.completesetting");
        registerReceiver(receiver, filter);
        }
    class CompleteReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			server = intent.getStringExtra("server");
			timeout = intent.getStringExtra("timeout");
		}  
    }
    private String login()
    {
    	URL url;
		try {
			//url = new URL("http://192.168.1.107/put_context/");
			url = new URL(server);
			//Toast.makeText(Client.this, server, Toast.LENGTH_LONG).show();
			URLConnection conn = url.openConnection();
		    conn.setDoOutput(true);
		    
		    BufferedWriter printout;
		    printout = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
		    printout.write("operation:login");
		    printout.newLine();
		    printout.flush();
		    printout.write("user:"+username);
		    printout.newLine();
		    printout.flush();
		    printout.write("password:"+password);
		    printout.newLine();
		    printout.flush();
		    printout.write("deviceid:"+m.get(username));
		    printout.newLine();
		    printout.flush();
		    printout.write("timeout:"+timeout);
		    printout.newLine();
		    printout.flush();
		    

		    
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    String line = "";
		    StringBuffer sb = new StringBuffer();
		    while ((line = rd.readLine()) != null) {
		    	sb.append(line);
		    }
		    return sb.toString();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
    }
    public boolean externalMemoryAvailable() {   
		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);  
	}
	public long getAvailableInternalMemorySize() {     
		File path = Environment.getDataDirectory();     
		StatFs stat = new StatFs(path.getPath());     
		long blockSize = stat.getBlockSize();     
		long availableBlocks = stat.getAvailableBlocks();     
		return availableBlocks * blockSize;     
	}     
	public long getTotalInternalMemorySize() {
		File path = Environment.getDataDirectory();     
		StatFs stat = new StatFs(path.getPath());     
		long blockSize = stat.getBlockSize();  
		long totalBlocks = stat.getBlockCount();     
		return totalBlocks * blockSize;
	}
	public long getAvailableExternalMemorySize() {
		if(externalMemoryAvailable()) {    
			File path = Environment.getExternalStorageDirectory();
			StatFs stat = new StatFs(path.getPath());     
			long blockSize = stat.getBlockSize();
			long availableBlocks = stat.getAvailableBlocks();     
			return availableBlocks * blockSize;
		}
		else
		{
			return -1;
		}
	}
	public long getTotalExternalMemorySize() {  
		if(externalMemoryAvailable()) { 
			File path = Environment.getExternalStorageDirectory();   
			StatFs stat = new StatFs(path.getPath());     
			long blockSize = stat.getBlockSize();     
			long totalBlocks = stat.getBlockCount();     
			return totalBlocks * blockSize;
		}
		else
		{
			return -1;
		}
	}
	public String formatSize(long size) {  
		if(size==-1)
		{
			return "There is no external memory";
		}
		String suffix = null;
		if (size >= 1024) {  
			suffix = "KB";
			size /= 1024; 
			if (size >= 1024) { 
				suffix = "MB";
				size /= 1024;
			}
		}
		StringBuilder resultBuffer = new StringBuilder(Long.toString(size)); 
		int commaOffset = resultBuffer.length() - 3; 
		while (commaOffset > 0) {     
			resultBuffer.insert(commaOffset, ',');    
			commaOffset -= 3;
		}
		if(suffix != null)
		{
			resultBuffer.append(suffix);     
		}
		return resultBuffer.toString();     
		
	}
    public String getInfo()
    {
    	//printout.write("info:memory={a=1,b=2}--os={a=3,b=4}--language={a=5,c=6}--location={a=7,c=9}--screen={a=10,b=109}");
    	StringBuilder sb = new StringBuilder();
		
		//memory
		String memory = "memory={total_external_memory="+formatSize(getTotalExternalMemorySize())+",free_external_memory="+formatSize(getAvailableExternalMemorySize())
		+",total_internal_memory="+formatSize(getTotalInternalMemorySize())+",free_internal_memory="+formatSize(getAvailableInternalMemorySize())+"}";
		sb.append(memory);
		sb.append("--");
		
		//os
		String os = "os={name="+System.getProperty("os.name")+",patch_level="+System.getProperty("sun.os.patch.level")+"}";
		sb.append(os);
		sb.append("--");
		
		//language
		String language = "language={user_language="+System.getProperty("user.language")+",file_encoding="+System.getProperty("file.encoding")+"}";
		sb.append(language);
		sb.append("--");
		
		//screen
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);	
		String screen = "screen={width="+dm.widthPixels+",height="+dm.heightPixels+"}";
		sb.append(screen);
		sb.append("--");
		
		//location;
		LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		Location l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);	
		String location = "location={latitude="+l.getLatitude()+",longitude="+l.getLongitude()+"}";
		sb.append(location);
		return sb.toString();

    }
    public String putInfo()
    {
    	String info = getInfo();
    	URL url;
		try {
			url = new URL(server);
			URLConnection conn = url.openConnection();
		    conn.setDoOutput(true);
		    
		    BufferedWriter printout;
		    printout = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
		    printout.write("operation:putinfo");
		    printout.newLine();
		    printout.flush();
		    printout.write("sessionid:"+sessionid);
		    printout.newLine();
		    printout.flush();
		    //printout.write("info:memory={a=1,b=2}--os={a=3,b=4}--language={a=5,c=6}--location={a=7,c=9}--screen={a=10,b=109}");
		    printout.write("info:"+info);
		    printout.newLine();
		    printout.flush();
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    String line = "";
		    StringBuffer sb = new StringBuffer();
		    while ((line = rd.readLine()) != null) {
		    	sb.append(line);
		    }
		    return sb.toString();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
    }
    class innerThread extends Thread
    {
		@Override
		public void run() {
			super.run();
			while(running)
			{
				String res = putInfo();
				if(!res.contains("ok"))
				{
					Button enter = (Button) findViewById(R.id.enter);				
					Button stop = (Button) findViewById(R.id.stop);
					stop.setClickable(false);
					enter.setClickable(true);
					running = false;
					break;
				}
				try {
					int t = Integer.valueOf(timeout);
					Thread.sleep(t*1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
    	
    }

}